<template>
  <el-container class="user-info-container">
    <el-descriptions
      v-loading="$fetchState.pending"
      :column="1"
      title="用户信息"
    >
      <el-descriptions-item label="用户id">
        {{ userInfo.id }}
      </el-descriptions-item>
      <el-descriptions-item label="用户名">
        {{ userInfo.username }}
      </el-descriptions-item>
      <el-descriptions-item label="用户邮箱">
        {{ userInfo.email }}
      </el-descriptions-item>
      <el-descriptions-item label="加入时间">
        {{ userInfo.createdAt }}
      </el-descriptions-item>
    </el-descriptions>
    <div>
      <el-button @click="logout">
        登出
      </el-button>
      <el-button type="danger" @click="terminate">
        注销
      </el-button>
    </div>
  </el-container>
</template>

<script>
import * as dayjs from 'dayjs';
import userApiBinder from '@/axios/user';
import { successMsg } from '@/utils/message';

export default {
  name: 'UserInfoPage',
  data() {
    return {
      userInfo: {}
    };
  },
  async fetch() {
    const {
      id, username, email, createdAt
    } = (await this.apis.getInfo()).data;
    this.userInfo = {
      id,
      username,
      email,
      createdAt: dayjs(createdAt).format('YYYY-MM-DD')
    };
  },
  created() {
    this.apis = userApiBinder(this);
  },
  fetchOnServer: false,
  methods: {
    async logout() {
      const res = await this.apis.logout();
      if (res.success) {
        successMsg('退出成功');
        await this.$router.push('/login');
      }
    },
    async terminate() {
      try {
        const { action } = await this.$prompt(
          '输入“确认删除”点击确认执行',
          '是否彻底删除用户所有数据',
          {
            inputValidator(value) {
              return value === '确认删除';
            }
          }
        );
        if (action === 'confirm') {
          await this.apis.del();
          successMsg('已经删除用户及相关数据');
          await this.$router.push('/login');
        }
      } catch (e) {
      }
    }
  }
};
</script>

<style scoped lang="scss">
.user-info-container {
  flex-direction: column;
  padding: 0 70px;
}
</style>
